package cn.com.libertymutual.core.database.druid.config;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import javax.sql.DataSource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.context.support.AbstractApplicationContext;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;

import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.spring.boot.autoconfigure.DruidDataSourceBuilder;

import cn.com.libertymutual.core.common.util.ApplicationContextUtil;

@Configuration
public class DataSourceConfiguration {
	private Logger log = LoggerFactory.getLogger(getClass());
    @Value("${spring.datasource.type}")
    private Class<? extends DataSource> dataSourceType;

	@Resource
	private AbstractApplicationContext applicationContext;
	
	@PostConstruct
	public void initApplicationContext() {
		try {
			ApplicationContextUtil.getInstance().init( applicationContext );
		}
		catch( Exception e ) {
			log.error("初始化applicationContext错误", e);
		}
	}
	
	
    @Primary
    @Bean(name="writeDataSource", destroyMethod = "close", initMethod = "init")
	@ConfigurationProperties("spring.datasource.druid.write")
	public DruidDataSource writeDruidDataSource(){
    	 log.info("-------------------- writeDataSource init ---------------------");
	    return DruidDataSourceBuilder.create().build();
	}
    @Bean(name="readDataSource1", destroyMethod = "close", initMethod = "init")
	@ConfigurationProperties("spring.datasource.druid.read1")
	public DruidDataSource readDruidDataSourceOne(){
    	 log.info("-------------------- readDataSource1 init ---------------------");
	    return DruidDataSourceBuilder.create().build();
	}
    @Bean(name="readDataSource2", destroyMethod = "close", initMethod = "init")
	@ConfigurationProperties("spring.datasource.druid.read2")
	public DruidDataSource readDruidDataSourceTwo(){
    	log.info("-------------------- readDataSource2 init ---------------------");
		return DruidDataSourceBuilder.create().build();
	}
    
    @Bean(name = "readJdbcTemplate")
    public JdbcTemplate wechatOrclJdbcTemplate(
    		@Qualifier("readDataSource1") DataSource dataSource) {
    	return new JdbcTemplate(dataSource);
    }
    
    
    @Bean(name = "readJdbcTemplate2")
    public NamedParameterJdbcTemplate JdbcTemplate(
    		@Qualifier("readDataSource2") DataSource dataSource) {
    	return new NamedParameterJdbcTemplate(dataSource);
    }
}
